from flask import Blueprint, request, jsonify
import json
from utils.db import db1
from .compan import get_data
import datetime
from utils.test_jwt import myjwt
from utils.acl import acl
from utils.redison import r
from .compan import xtree

bp_users = Blueprint('users', __name__)


@bp_users.route('/user', methods=['POST', 'GET'])
def user():
    if request.method == 'POST':
        data = get_data()
        print(data)
        createtime = datetime.datetime.strftime(datetime.datetime.now(), "%Y%m%d%H%M%S")
        sql1 = '''insert into users(name,gonghao,ygcode,shiti,mobile,sex,pic,username,password,del_type,createman,createtime,gangweiid,gongsiid,zhiwuid) values("%s","%s","%s",%d,"%s",%d,"%s","%s","%s","%s","%s","%s",%d,%d,%d)''' % (
            data['name'], data['gonghao'], data['ygcode'], int(data['shiti']), data['mobile'], int(data['sex']),
            data['pic'], data['username'], data['password'], int(1), 'admin', createtime, int(data['gangweiid']),
            int(data['gongsiid']), int(data['zhiwuid']))
        print(sql1)
        db1.update(sql1)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        sql2 = 'select * from users'
        res = db1.findall(sql2)
        return jsonify({'code': 200, 'list': res})


@bp_users.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        data = get_data()
        sql1 = 'select username,id,password from users where username = "%s"' % (data['username'])
        res = db1.findone(sql1)
        if res:
            if int(data['password']) == int(res['password']):
                token = myjwt.encode_jwt({'data': {'userid': res['id']}})
                vuelist = acl.get_vue(int(res['id']))

                flasklist = acl.get_flask(int(res['id']))
                key = '2104' + str(res['id'])
                r.insert_set(key, flasklist)

                return jsonify(
                    {'code': 200, 'userid': res['id'], 'token': token, 'username': res['username'], 'vuelist': vuelist})
            else:
                return jsonify({"code": 20010, 'mes': '密码错误'})
        else:
            return jsonify({'code': 20011, 'mes': '用户名错误'})

    elif request.method == 'GET':
        id = request.args.get('userid')
        sql = 'select * from resource as r join user_resource as ur on r.id=ur.resourceid where ur.userid=%d and r.type = 1' % (
            int(id))
        res = db1.findall(sql)
        list1 = []
        list2 = []
        for i in res:
            if i['pid'] == 0:
                list1.append(i)
            else:
                list2.append(i)
        return jsonify({'code': 200, 'list1': list1, 'list2': list2})


@bp_users.route('/resource', methods=['GET', 'POST'])
def resource():
    if request.method == 'GET':
        sql = """ select * from resource """
        res = db1.findall(sql)
        ziyuan = xtree(res)
        sql1 = """select id,name from users """
        res1 = db1.findall(sql1)
        users = []
        for i in res1:
            dict = {}
            dict['label'] = i['name']
            dict['value'] = str(i['id'])
            users.append(dict)
        return jsonify({'code': 200, 'ziyuan': ziyuan, 'users': users})
    elif request.method == 'POST':
        data = get_data()
        print(data)
        return 'ok'


@bp_users.route('/add_jszy', methods=['POST'])
def add_jszt():
    if request.method == 'POST':

        gain = get_data()
        # print(gain)
        list2 = []
        for i in gain['list']:
            list2.append(int(i))
        list1 = set(list2[1:])
        sql1 = """select * from user_resource where userid=%d""" % (int(gain['user_id']))
        res1 = db1.findone(sql1)

        if res1:
            acl.put_resoutce(gain['user_id'], list1)
        else:
            acl.add_resoutce(gain['user_id'], list1)
        return jsonify({"code": 200})


# 获取角色
@bp_users.route('/juese', methods=['POST', 'GET'])
def juese():
    if request.method == 'GET':
        sql1 = 'select * from roles'
        res1 = db1.findall(sql1)
        juese = []
        for i in res1:
            dict = {}
            dict['label'] = i['name']
            dict['value'] = str(i['id'])
            juese.append(dict)
        return jsonify({'code': 200, 'juese': juese})
    elif request.method == 'POST':
        gain = get_data()
        print(gain)
        list2 = []
        for i in gain['list']:
            list2.append(int(i))
        list1 = set(list2[1:])
        print(list1)
        sql1 = """select * from role_resource where roleid = %d""" % (int(gain['roleid']))
        res1 = db1.findone(sql1)
        if res1:
            sql2 = 'delete from role_resource where roleid = %d ' % (int(gain['roleid']))
            db1.update(sql2)
            for i in list1:
                sql3 = 'insert into role_resource(roleid,resourceid) values(%d,%d)' % (int(gain['roleid']), int(i))
                db1.update(sql3)
        else:
            for i in list1:
                sql4 = 'insert into role_resource(roleid,resourceid) values(%d,%d)' % (int(gain['roleid']), int(i))
                db1.update(sql4)
        return jsonify({'code': 200})


# 添加用户的时候获取角色
@bp_users.route('/role', methods=['GET', 'POST'])
def role():
    if request.method == 'GET':
        sql = 'select * from roles'
        res = db1.findall(sql)
        return jsonify({'code': 200, 'list': res})
    elif request.method == 'POST':
        data = get_data()
        # print(data)
        print(data['rolelist'], data['userid'])
        sql = 'select roleid from user_role where userid = %d' % (int(data['userid']))
        res = db1.findall(sql)
        if res:
            sql = 'delete from user_role where userid = %d' % (int(data['userid']))
            db1.update(sql)
            for i in json.loads(data['rolelist']):
                print(type(json.loads(data['rolelist'])))
                for j in json.loads(data['rolelist']):
                    sql2 = 'select id from huchi where roleid1 = %d and roleid2 = %d' % (int(i), int(j))

                    res2 = db1.findall(sql2)
                    if res2:
                        continue
                    else:
                        print(j)
                        sql3 = 'insert into user_role(userid,roleid) values(%d,%d)' % (int(data['userid']), int(j))
                        db1.update(sql3)
                return jsonify({'code': 200})
        else:
            for i in json.loads(data['rolelist']):
                print(type(json.loads(data['rolelist'])))
                for j in json.loads(data['rolelist']):
                    sql2 = 'select id from huchi where roleid1 = %d and roleid2 = %d' % (int(i), int(j))

                    res2 = db1.findall(sql2)
                    if res2:
                        continue
                    else:
                        print(j)
                        sql3 = 'insert into user_role(userid,roleid) values(%d,%d)' % (int(data['userid']), int(j))
                        db1.update(sql3)
                return jsonify({'code': 200})
